﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
using EHTWebsiteProject.Code.BLL;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace EHTWebsiteProject.Administrator
{
    public partial class EHTArticleIU : System.Web.UI.Page
    {
        public Boolean IsVN = true;
        private String message = "";
        private String languageCode = "vi-VN";
        private DataTable dtProductCategorys = new DataTable();
        private ResourceManager rm = new ResourceManager("Resources.SiteMap", System.Reflection.Assembly.Load("App_GlobalResources"));
        private Int32 TinTucID = -1;
        private String TomTatVN = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["UserName"] == null)
                    Response.Redirect("../Account/EHTLogin.aspx");
                else
                {
                    dtProductCategorys = DanhMucTinTucProvider.GetDanhMucTinTuc().Tables[0];
                    try
                    {
                        languageCode = Session[HangSo.LANGUAGE_CODE].ToString();
                        if (languageCode == "en-us")
                        {
                            IsVN = false;
                        }

                    }
                    catch (Exception ex)
                    {
                    }

                    try
                    {
                        TinTucID = Int32.Parse(Request.QueryString["TinTucID"]);
                    }
                    catch
                    {

                    }

                    try
                    {
                        message = Request.QueryString["Message"].ToString();
                        if (message != "")
                            ltrErorr.Text = HelpMethod.ApplySuccess(message);
                    }
                    catch
                    {

                    }
                    Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCode);
                    LoadLanguage(Thread.CurrentThread.CurrentCulture);
                    CreateDDLCategory(0, 0);
                  

                    if (IsVN == true)
                        this.ddlDanhMucTinTuc.Items.Insert(0, new ListItem(HangSo.DanhMuc, "0"));
                    else
                        this.ddlDanhMucTinTuc.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "0"));

                    if (TinTucID != -1)
                    {
                        ViewState["action"] = HangSo.ACTION_UPDATE;
                        ViewState["TinTucID"] = TinTucID.ToString();
                        if (IsVN == true)
                            lbAdd_Edit.Text = HangSo.Edit_VN;
                        else
                            lbAdd_Edit.Text = HangSo.Edit_Other;
                        LoadTinTuc(TinTucID);

                    }
                    else
                    {
                        ViewState["action"] = HangSo.ACTION_ADD;
                        if (IsVN == true)
                            lbAdd_Edit.Text = HangSo.Add_VN;
                        else
                            lbAdd_Edit.Text = HangSo.Add_Other;
                    }
                }
            }
        }

        /// <summary>
        ///  Hàm lấy tin theo ID và gán vào html
        /// </summary>
        /// <param name="TinTucID"></param>
         public void LoadTinTuc(Int32 TinTucID)
        {
            TinTuc TheTinTuc = TinTucProvider.GetTinTucByTinTucID(TinTucID);
            txtSapXep.Text = TheTinTuc.SapXep.ToString();
            txtTieuDeOther.Text = TheTinTuc.TieuDeOther;
            txtTieuDeVN.Text = TheTinTuc.TieuDeVN;
            txtImage.Text = TheTinTuc.HinhAnhUrl;
            ddlDanhMucTinTuc.SelectedValue = TheTinTuc.DanhMucTinTucID.ToString();            

            //kiểm tra trường tóm tắt           
            if (TheTinTuc.TomTatOther != "")
                //nếu tồn tại thì hiển thị chữ màu vàng
                RadNoiDungOther.Content = TheTinTuc.TomTatOther + "-------" + TheTinTuc.NoiDungOther;
            else
                RadNoiDungOther.Content = TheTinTuc.NoiDungOther;

            if (TheTinTuc.TomTatVN != "")
                //nếu tồn tại thì hiển thị chữ màu vàng
                RadNoiDUngVN.Content = TheTinTuc.TomTatVN + "-------" + TheTinTuc.NoiDungVN;
            else
                RadNoiDUngVN.Content = TheTinTuc.NoiDungVN;
            
           
    
            imgHinhAnh.ImageUrl = "~/ImageDatas/News/"+TheTinTuc.HinhAnhUrl;
            chkNoiBat.Checked = TheTinTuc.NoiBat;
            ViewState["HinhAnhUrl"] = TheTinTuc.HinhAnhUrl;
        }
       

        /// <summary>
        /// Ham load ngon ngu
        /// </summary>
        /// <param name="ci"></param>
        public void LoadLanguage(CultureInfo ci)
        {
            lbApply.Text = rm.GetString("lbApply",ci);
            lbArticles.Text = rm.GetString("lbArticles", ci);
            lbCancel.Text = rm.GetString("lbCancel", ci);
            lbHelp.Text = rm.GetString("lbHelp", ci);
            lbSave.Text = rm.GetString("lbSave", ci);
            lbDanhMucTinTuc.Text = rm.GetString("lbDanhMucTinTuc", ci);
            lbMenuNameVN.Text = rm.GetString("lbMenuNameVN", ci);
            lbMenuNameOther.Text = rm.GetString("lbMenuNameOther", ci);
            lbHinhAnh.Text = rm.GetString("lbHinhAnh",ci);
            lbThuTu.Text = rm.GetString("lbThuTu", ci);
            lbNoiDungVN.Text = rm.GetString("lbNoiDungVN", ci);
            lbNoiDungOther.Text = rm.GetString("lbNoiDungOther", ci);
            chkNoiBat.Text = rm.GetString("chkNoiBat",ci);            
        }

        /// <summary>
        /// Ham load danh muc san pham
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateDDLCategory(Int32 ChuyenMucChaID, Int32 level)
        {
            String preString = "";

            for (Int32 i = 0; i < level; ++i)
            {
                preString += "--";
            }

            DataRow[] drCategorysSub = dtProductCategorys.Select("ChuyenMucChaID = " + ChuyenMucChaID.ToString());
            Int32 amountOfCategorySub = drCategorysSub.Count();

            //Điểm dừng đệ quy
            if (amountOfCategorySub == 0)
                return;

            for (Int32 i = 0; i < amountOfCategorySub; ++i)
            {
                Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["DanhMucTinTucID"].ToString());
                ListItem li;
                if (IsVN == true)
                    li = new ListItem(preString + drCategorysSub[i]["TenDanhMucTinTucVN"].ToString(), drCategorysSub[i]["DanhMucTinTucID"].ToString());
                else
                    li = new ListItem(preString + drCategorysSub[i]["TenDanhMucTinTucOther"].ToString(), drCategorysSub[i]["DanhMucTinTucID"].ToString());
                this.ddlDanhMucTinTuc.Items.Add(li);
                CreateDDLCategory(subCategoryID, level + 1);
            }
        }

        /// <summary>
        /// Hàm validate dữ liệu trước khi fill vào database
        /// </summary>
        /// <returns></returns>
        public Boolean validateData()
        {
            Boolean flag = true;
            //if (txtTieuDeOther.Text == "")
            //{
            //    if (IsVN == true)
            //        message = HangSo.check_VN;
            //    else
            //        message = HangSo.check_Other;
            //    return false;
            //}
            if (txtTieuDeVN.Text == "")
            {
                if (IsVN == true)
                    message = HangSo.check_VN;
                else
                    message = HangSo.check_Other;
                return false;
            }
            if (ddlDanhMucTinTuc.SelectedValue == "-1")
            {
                if (IsVN == true)
                    message = HangSo.meagessddl;
                else
                    message = HangSo.meagessddlOther;
                return false;
            }
            else
            {
                // kiểm tra xem sanh mục có phải là danh mục cha hay ko?
                // nếu là danh mục cha thì không được phép thêm tin tức
                DataSet ds = DanhMucTinTucProvider.GetDanhMucTinTucsByNhomDanhMucID(Int32.Parse(ddlDanhMucTinTuc.SelectedValue));
                if (ds.Tables[0].Rows.Count > 1)
                {
                    if (IsVN == true)
                        message = HangSo.Eorr_Add;
                    else
                        message = HangSo.Eorr_AddOther;
                    return false;
                }
                
            }

            return flag;
        }

        /// <summary>
        /// Hàm apply
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImgApply_Click(object sender, ImageClickEventArgs e)
        {
            String action = ViewState["action"].ToString();
            Int32 TinTucIDOut = 0;
            if (validateData() == false)
            {
                ltrErorr.Text = HelpMethod.ErorrLogin(message);
                return;
            }
            else
            {
                TinTuc theTinTuc = new TinTuc();
                theTinTuc.DanhMucTinTucID = Int32.Parse(ddlDanhMucTinTuc.SelectedValue);
                theTinTuc.TieuDeOther = txtTieuDeOther.Text;
                theTinTuc.TieuDeVN = txtTieuDeVN.Text;
                theTinTuc.HinhAnhUrl = txtImage.Text;
                theTinTuc.LoaiTin = -1;
                //lấy chỉ số của chuỗi từ đâu đến khi gặp chuỗi -------
                int index1 = RadNoiDungOther.Content.IndexOf("------");
                int index2 = RadNoiDUngVN.Content.IndexOf("------");
                try
                {
                    // tóm tăt
                    theTinTuc.TomTatOther = RadNoiDungOther.Content.Substring(0, index1).ToString();
                    // nội dung
                    theTinTuc.NoiDungOther = RadNoiDungOther.Content.Remove(0, index1 + 7).ToString();
                }
                catch
                {
                    theTinTuc.TomTatOther = "";
                    theTinTuc.NoiDungOther = RadNoiDungOther.Content;
                }

                try
                {
                    theTinTuc.TomTatVN = RadNoiDUngVN.Content.Substring(0, index2).ToString();
                    theTinTuc.NoiDungVN = RadNoiDUngVN.Content.Remove(0, index2 + 7).ToString();
                }
                catch
                {
                    theTinTuc.TomTatVN = "";
                    theTinTuc.NoiDungVN = RadNoiDUngVN.Content;
                }
                theTinTuc.NoiBat = chkNoiBat.Checked;
                try
                {
                    theTinTuc.SapXep = Int32.Parse(txtSapXep.Text);
                }
                catch
                {
                    theTinTuc.SapXep = 1;
                }




                if (action == HangSo.ACTION_ADD)
                {
                    theTinTuc.TinTucID = -1;
                    TinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, true);
                }
                else
                {
                    theTinTuc.TinTucID = Int32.Parse(ViewState["TinTucID"].ToString());
                    TinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, false);
                }
            }
            String str = "";
            if (IsVN == true)
                str = HangSo.App_VN;
            else
                str = HangSo.App_Other;
            Response.Redirect("EHTArticleIU.aspx?TinTucID=" + TinTucIDOut.ToString() + "&&Message=" + str);
        }

        /// <summary>
        /// Ham save
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImgSave_Click(object sender, ImageClickEventArgs e)
        {
            String action = ViewState["action"].ToString();
            Int32 TinTucIDOut = 0;
            if (validateData() == false)
            {
                ltrErorr.Text = HelpMethod.ErorrLogin(message);
                return;
            }
            else
            {
                TinTuc theTinTuc = new TinTuc();
                theTinTuc.DanhMucTinTucID = Int32.Parse(ddlDanhMucTinTuc.SelectedValue);
                theTinTuc.TieuDeOther = txtTieuDeOther.Text;
                theTinTuc.TieuDeVN = txtTieuDeVN.Text;
                theTinTuc.HinhAnhUrl = txtImage.Text;
                theTinTuc.LoaiTin = -1;

                int index1 = RadNoiDungOther.Content.IndexOf("------");
                int index2 = RadNoiDUngVN.Content.IndexOf("------");
                try
                {
                    theTinTuc.TomTatOther = RadNoiDungOther.Content.Substring(0, index1).ToString();
                    theTinTuc.NoiDungOther = RadNoiDungOther.Content.Remove(0, index1 + 7).ToString();
                }
                catch
                {
                    theTinTuc.TomTatOther = "";
                    theTinTuc.NoiDungOther = RadNoiDungOther.Content;
                }

                try
                {
                    theTinTuc.TomTatVN = RadNoiDUngVN.Content.Substring(0, index2).ToString();
                    theTinTuc.NoiDungVN = RadNoiDUngVN.Content.Remove(0, index2 + 7).ToString();
                }
                catch
                {
                    theTinTuc.TomTatVN = "";
                    theTinTuc.NoiDungVN = RadNoiDUngVN.Content;
                }
                theTinTuc.NoiBat = chkNoiBat.Checked;
                try
                {
                    theTinTuc.SapXep = Int32.Parse(txtSapXep.Text);
                }
                catch
                {
                    theTinTuc.SapXep = 1;
                }

                if (action == HangSo.ACTION_ADD)
                {
                    theTinTuc.TinTucID = -1;
                    TinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, true);
                }
                else
                {
                    theTinTuc.TinTucID = Int32.Parse(ViewState["TinTucID"].ToString());
                    TinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, false);
                }
            }
            Response.Redirect("EHTArticle.aspx");
        }

        /// <summary>
        /// hàm uplpad ảnh
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            String action = ViewState["action"].ToString();
            if (this.fuHinhAnhUrl.HasFile)
            {
                String fileName = fuHinhAnhUrl.PostedFile.FileName;
                String pathAvatars = Server.MapPath("~/");
                String fileType = Path.GetExtension(fileName);
                String FileNewName = DateTime.Now.Ticks.ToString() + fileType;
                try
                {
                    //hàm vẽ lại ảnh nếu kích thước lớn hơn kích thước quy định
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fuHinhAnhUrl.PostedFile.InputStream);
                    if (Int32.Parse(oImg.Width.ToString()) > 1000)
                    {


                        int thumbWidth = 1000;
                        int thumbHeight = (Int32.Parse(oImg.Height.ToString()) * thumbWidth) / (Int32.Parse(oImg.Width.ToString()));
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);
                        oThumbNail.Save(pathAvatars + "\\ImageDatas\\News\\" + FileNewName);
                        oImg.Dispose();
                    }

                    else
                    {

                        this.fuHinhAnhUrl.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//News//" + FileNewName);
                    }
                    txtImage.Text = FileNewName;
                    imgHinhAnh.ImageUrl = "~\\ImageDatas\\News\\" + FileNewName;
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {
                    txtImage.Text = ViewState["HinhAnhUrl"].ToString();
                }
                else
                {
                    txtImage.Text = "noImage.gif";
                }
            }
        }
        
        
    }
}